package com.framework.network.interceptor

import com.framework.network.annotations.getRetrofitMethod
import com.framework.network.annotations.getTimeOut
import com.framework.network.annotations.getTimeOutParameter
import okhttp3.Interceptor
import okhttp3.Response
import java.util.concurrent.TimeUnit

/**
 * @Description:设置请求超时时间
 * @Author: you
 */
class DynamicTimeoutInterceptor : Interceptor {
    companion object {
        const val TIMEOUT = 30
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        // 获取 retrofit 中定义 method
        val retrofitMethod = getRetrofitMethod(request) ?: return chain.proceed(request)
        // 根据 method 获取它的 TimeOut 注解
        val setTimeOut = getTimeOut(retrofitMethod)
        val timeout = if (setTimeOut != null) {
            getTimeOutParameter(setTimeOut)
        } else {
            TIMEOUT
        }
        return chain.withConnectTimeout(timeout, TimeUnit.SECONDS)
            .withReadTimeout(timeout, TimeUnit.SECONDS)
            .withWriteTimeout(timeout, TimeUnit.SECONDS)
            .proceed(request)
    }
}